<?php

namespace app\common\controller;

use think\facade\Cookie;
use think\facade\View;

class PayBackend extends CommonBase
{
    // 模型
    protected $model;
    // 服务
    protected $service;
    // 校验
    protected $validate;
    // 用户ID
    protected $userId;
    // 用户登录信息
    protected $userInfo;
    protected $myAppInfo;
    protected $myPowerInfo;
    // 网络请求
    protected $param;

    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        // 初始化登录信息
        $this->initLogin();
    }


    /**
     * 校验登录
     * @author 陌上花开
     * @since: 2022/01/19
     */
    public function initLogin()
    {
        try{
            $userId = cookie('userId');
            $sign = cookie('userSign');
            $this->userId = $userId;

            // 登录用户信息
            $userModel = new \app\user\model\User();
            $userInfo = $userModel->getInfo();
            $this->userInfo = $userInfo;
            if(!empty($userId) && $sign != data_auth_sign($this->userInfo['appid'].$this->userInfo['username'].$this->userInfo['password'].sf_password_hash())){
                throw new Exception('用户登录信息已过期，请刷新界面重新登录！');
            }
            if(!$this->userInfo){
                $this->logOut();
                return;
            }
            
            if(empty($this->userInfo['appid'])){
                $this->logOut();
                return;
            }
            if(!is_numeric($this->userInfo['appid']) || $this->userInfo['appid'] <= 0){
                $this->logOut();
                return;
            }
            if($this->userInfo['status'] != 1){
                $this->logOut();
                return;
            }
            if(!empty($this->userInfo['ip'])){
                if(!in_array(get_client_ip(),unserialize($userInfo['ip']))){
                    $this->logOut();
                    return;
                }
            }
            // 数据绑定
            View::assign('userId', $this->userId);
            View::assign('userInfo', $this->userInfo);
        }catch (\Exception $e){
            if(IS_POST){
                exit(json_encode(message($e->getMessage(), false)));
            }
            exit($this->render('/public/error', ['msg' => $e->getMessage()]));
        }
    }

    /**
     * 退出登录
     * @author 陌上花开
     * @since: 2022/01/19
     */
    public function logOut(){
        $content = [
            'Title' => '退出登录',
            'Result' => 'success'
        ];
        event('ActionLog', $content);
        Cookie::delete('userId');
        Cookie::delete('userSign');
        Cookie::save();
        return message('退出登录成功', false);
    }
}